# coding=utf-8

import os
import sys
import gettext
import web
import settings

# object used to store all translations.
allTranslations = web.storage()

def get_translations(lang):
	# init translation.
	if allTranslations.has_key(lang):
		translation = allTranslations[lang]
	elif lang is None:
	 	translation = gettext.NullTranslations()
	else:
		try:
			translation = gettext.translation(
						'messages',
						settings.LOCALE_DIR,
						languages=[lang],
					)
		except IOError:
			translation = gettext.NullTranslations()
	return translation

def load_translations(lang):
	"""Return the translations for the locals."""
	lang = str(lang)
	translation = allTranslations.get(lang)
	if translation is None:
		translation = get_translations(lang)
		allTranslations[lang] = translation

		# Delete unused translations.
		for lk in allTranslations.keys():
			if lk != lang:
				del allTranslations[lk]
	return translation

def custom_gettext(string):
	"""Translate a given string to the language of the application."""
	# 是否启用i18n
	if not settings.USE_I18N:
		return unicode(string, 'utf-8')

	translation = load_translations(web.cookies().get('lang', settings.LANGUAGE_CODE))
	if translation is None:
		return unicode(string, 'utf-8')

	return translation.ugettext(unicode(string, 'utf-8'))

# simple handle
_ = custom_gettext

# 方便模板中调用
web.template.Template.globals['_'] = _
